package com.lglin.service.admin.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lglin.bean.product.entity.Category;
import com.lglin.bean.product.entity.Product;
import com.lglin.bean.user.entity.User;
import com.lglin.common.constant.Constant;
import com.lglin.common.utils.other.QiniuCloudUtil;
import com.lglin.dao.admin.AdminDao;
import com.lglin.dao.user.UserDao;
import com.lglin.dao.user.UserRoleDao;
import com.lglin.service.admin.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Override
    public PageInfo<User> selectUser(int pageNum) {
        Page<User> page = PageHelper.startPage(pageNum, Constant.PageSize);
        adminDao.selectUser();
        PageInfo<User> info = new PageInfo<User>(page);
        return info;
    }

    @Override
    public PageInfo<User> searchUser(String start, String end, String username, int pageNum) {
        Page<User> page = PageHelper.startPage(pageNum, Constant.PageSize);
        if (start.equals("") && end.equals("") && username.equals("")) {
            adminDao.selectUser();
            PageInfo<User> info = new PageInfo<User>(page);
            return info;
        }
        System.out.println(start);
        System.out.println(end);
        System.out.println(username);

        Map<String, String> map = new HashMap<>();
        if (!username.equals("")) {
            map.put("searchKey", "email");
            map.put("email", username);
        } else {
            map.put("searchKey", "time");
            map.put("start", start);
            map.put("end", end);
        }
        System.out.println(map);

        adminDao.searchUser(map);
        PageInfo<User> info = new PageInfo<User>(page);
        return info;
    }

    @Override
    public boolean addUser(User user) {
        user.setImg(Constant.DEFAULT_IMG);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        int result = userDao.register(user);
        if (result > 0) {
            return userRoleDao.addUserRoleRelate(user) > 0;
        }
        return false;
    }

    @Override
    public boolean updateUserInfo(User user) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        int result = adminDao.updateUserInfo(user);
        return result > 0;
    }

    @Override
    public boolean deleteUser(String ids) {
        int result = adminDao.deleteUser(ids);
        return result > 0;
    }

    @Override
    public PageInfo<Map<String, Object>> selectOrderList(int pageNum) {
        Page<Map<String, Object>> page = PageHelper.startPage(pageNum, Constant.PageSize);
        adminDao.orderList();
        PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(page);
        return info;
    }

    @Override
    public boolean deleteOrder(String ids) {
        int result = adminDao.deleteOrder(ids);
        return result > 0;
    }

    @Override
    public PageInfo<Map<String, Object>> searchOrder(String start, String end, String sid, int pageNum) {
        Page<Map<String, Object>> page = PageHelper.startPage(pageNum, Constant.PageSize);
        if (start.equals("") && end.equals("") && sid.equals("")) {
            adminDao.orderList();
            PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(page);
            return info;
        }
        Map<String, String> map = new HashMap<>();
        if (!sid.equals("")) {
            map.put("searchKey", "sid");
            map.put("sid", sid);
        } else {
            map.put("searchKey", "time");
            map.put("start", start);
            map.put("end", end);
        }
        System.out.println(map);
        adminDao.searchOrder(map);
        PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(page);
        return info;
    }

    @Override
    public PageInfo<Map<String, Object>> searchProduct(String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        int pageNum = jsonObject.getInteger("pageNum");
        String key = jsonObject.getString("key");
        Page<Map<String, Object>> page = PageHelper.startPage(pageNum, Constant.PageSize);
        adminDao.searchProduct(key);
        PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(page);
        return info;
    }

    @Override
    public int addProduct(String data) {
        Map<String, Object> map = JSONObject.parseObject(data, Map.class);
        System.out.println(map);
        int result = adminDao.addProduct(map);
        if (result > 0) {
            System.out.println(map.get("id"));
            String cids = map.get("cids").toString();
            if (Integer.parseInt(map.get("new_price").toString()) < 100)
                cids += "-8";
            if (Integer.parseInt(map.get("new_price").toString()) >= 100 && Integer.parseInt(map.get("new_price").toString()) < 300)
                cids += "-9";
            if (Integer.parseInt(map.get("new_price").toString()) >= 300 && Integer.parseInt(map.get("new_price").toString()) < 500)
                cids += "-10";
            if (Integer.parseInt(map.get("new_price").toString()) >= 500 && Integer.parseInt(map.get("new_price").toString()) < 1000)
                cids += "-11";
            if (Integer.parseInt(map.get("new_price").toString()) >= 1000 && Integer.parseInt(map.get("new_price").toString()) < 2000)
                cids += "-12";
            if (adminDao.addProductCategory(Integer.parseInt(map.get("id").toString()), splitData(cids)) > 0) {
                return Integer.parseInt(map.get("id").toString());
            }
        }
        return 0;
    }

    @Override
    public Map<String, Object> getProductInfo(int id) {
        return adminDao.getProductInfo(id);
    }

    @Override
    public boolean updateProduct(String data) {
        Map<String, Object> map = JSONObject.parseObject(data, Map.class);
        System.out.println(map);
        int result = adminDao.updateProduct(map);
        if (result > 0) return true;
        return false;
    }

    @Override
    public boolean deleteProduct(int id) {
        int result = adminDao.deleteProduct(id);
        if (result > 0) return adminDao.deleteProductCategry(id) > 0;
        return false;
    }

    @Override
    public List<Category> productCategory() {
        return adminDao.getCategory();
    }

    @Override
    public boolean addCategory(Category category) {
        return adminDao.addCategory(category.getName()) > 0;
    }

    @Override
    public boolean deleteCategory(int id) {
        if (adminDao.deleteCategory(id) > 0) return true;
        return false;
    }

    @Override
    public PageInfo getCategory(int pageNum) {
        Page<Category> page = PageHelper.startPage(pageNum, Constant.PageSize);
        adminDao.getCategory();
        PageInfo<Category> info = new PageInfo<Category>(page);
        return info;
    }

    @Override
    public boolean upload(MultipartFile[] file, int id) {
        String[] imgs = new String[file.length];
        for (int i = 0; i < file.length; i ++) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String img = formatter.format(new Date()) + randomStr();
            imgs[i] = Constant.IMG_URl + img;
            System.out.println(img);
            QiniuCloudUtil.uploadFile(file[i],img);
        }
        return adminDao.addPic(id, imgs) > 0;
    }

    @Override
    public boolean updateOrderStatus(int id, int status) {
        return adminDao.updateOrderStatus(id, status) > 0;
    }

    private static int[] splitData(String data) {
        String[] strArray = data.split("-");
        return Arrays.stream(strArray).mapToInt(Integer::parseInt).toArray();
    }

    private static String randomStr() {
        String str = "";
        for (int i = 0; i < 5; i++) {
            str += (int) (Math.random()*(10-1)+1);
        }
        return str;
    }

}
